<template>
  <view class="container">
    <!-- 表单主体 -->
    <uni-forms ref="form" :modelValue="formData" :rules="rules">
      <!-- 真实姓名 -->
      <uni-forms-item  label="姓名 *" name="name">
        <uni-easyinput type="text" v-model="formData.name" placeholder="请输入真实姓名" :maxlength="20" />
      </uni-forms-item>
      <!-- 学号 -->
      <uni-forms-item label="学号 *" name="studentId">
        <uni-easyinput type="text" v-model="formData.studentId" placeholder="请输入学号" :maxlength="30" />
      </uni-forms-item>
      <!-- 联系方式 -->
      <uni-forms-item label="联系方式" name="contact">
        <uni-easyinput type="text" v-model="formData.contact" placeholder="请输入联系方式" :maxlength="50" />
      </uni-forms-item>
      <!-- 提交时间（这里使用默认值，页面上不显示输入框） -->
	  <uni-forms-item>
	  	<view class="example-body">
	  				<uni-datetime-picker type="date" :clear-icon="false" v-model="formData.submitTime" @maskClick="maskClick" />
	  			</view>
	  </uni-forms-item>
      <!-- 工作文件路径 -->
	  <uni-forms-item label="文件标题" name="title">
	    <uni-easyinput type="text" v-model="formData.title" placeholder="请输入文件标题" :maxlength="100" />
	  </uni-forms-item>
      <uni-forms-item label="工作文件">
        <uni-file-picker v-model="fileList" limit="5" fileMediatype="all" :image-styles="imageStyles"
          @select="selectFile" @delete="deleteFile" />
        <text style="font-size: 12px; color: red;">单个大小不超过 5MB \n
          格式为 doc/xls/ppt/pdf 的文件</text>
      </uni-forms-item>
      <!-- 是否可批注 -->
      <uni-forms-item label="是否成功" name="canAnnotate">
        <uni-data-checkbox :localdata="annotationOptions" v-model="formData.canAnnotate" mode="button" />
      </uni-forms-item>
      <!-- 不可原因 -->
      <uni-forms-item v-if="formData.canAnnotate === '0'" label="不可原因" name="cause">
        <uni-easyinput type="textarea" v-model="formData.cause" placeholder="请输入不可原因" :maxlength="500"
          autoHeight />
      </uni-forms-item>
      <!-- 分组编号 -->
      <uni-forms-item label="组号 *" name="groupNum">
        <uni-easyinput type="text" v-model="formData.groupNum" placeholder="请输入组别(第一组输入:1)" :maxlength="5" />
      </uni-forms-item>
      <!-- 备注 -->
   <!--   <uni-forms-item label="备注" name="remark">
        <uni-easyinput type="textarea" v-model="formData.remark" placeholder="请输入备注" :maxlength="500"
          autoHeight />
      </uni-forms-item> -->
   
      <!-- 状态 -->
    <!--  <uni-forms-item label="状态" name="status">
        <uni-data-checkbox :localdata="statusOptions" v-model="formData.status" mode="button" />
      </uni-forms-item> -->
     
      <!-- 用户 ID（这里假设用户 ID 是已知的，直接设置在表单数据中） -->
      <!-- <input type="hidden" v-model="formData.user_id" /> -->
    </uni-forms>
    <!-- 提交按钮 -->
    <button class="submit-btn" @click="submit" >提交审核</button>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onReady } from '@dcloudio/uni-app'
import { http } from '../../../utils/requestUtil';

// 表单数据模型
const formData = reactive({
  name: '',
  studentId: '',
  title:'',
  submitTime:'',
  contact: '',
  workFile: '',
  canAnnotate: '0', // 默认不可批注
  cause: '',
  groupNum: '',
  remark: '',
  status: '0', // 默认待审
  workload: 0,
  // user_id: 1, // 假设用户 ID 为 1，实际需要从登录信息等获取
  tempFile: [],
  files: ''
})

// 文件列表管理
const fileList = ref([])
const imageStyles = {
  height: 160,
  width: 160,
  border: {
    color: '#eee',
    width: 2,
    style: 'dashed'
  }
}

// 批注选项
const annotationOptions = [
  {
    value: '0',
    text: '否'
  },
  {
    value: '1',
    text: '是'
  }
]

// 状态选项
const statusOptions = [
  {
    value: '0',
    text: '待审'
  },
  {
    value: '1',
    text: '通过'
  },
  {
    value: '2',
    text: '不通过'
  }
]

// 验证规则
const rules = {
  name: {
    rules: [{
      required: true,
      errorMessage: '请输入真实姓名'
    }, {
      validateFunction: (rule, value) => value.length <= 20,
      errorMessage: '真实姓名最多20字'
    }]
  },
  studentId: {
    rules: [{
      required: true,
      errorMessage: '请输入学号'
    }, {
      validateFunction: (rule, value) => value.length <= 30,
      errorMessage: '学号最多30字'
    }]
  },
  contact: {
    rules: [{
      validateFunction: (rule, value) => value.length <= 50,
      errorMessage: '联系方式最多50字'
    }]
  },
  canAnnotate: {
    rules: [{
      required: true,
      errorMessage: '请选择是否可批注'
    }]
  },
  groupNum: {
    rules: [{
      required: true,
      errorMessage: '请输入分组编号'
    }, {
      validateFunction: (rule, value) => value.length <= 5,
      errorMessage: '分组编号最多5字'
    }]
  },
  remark: {
    rules: [{
      validateFunction: (rule, value) => value.length <= 500,
      errorMessage: '备注最多500字'
    }]
  }
}

const maskClick = (e) => {
  console.log(e)
}

// 文件操作
const selectFile = async (files) => {
  console.log(files.tempFilePaths)
  formData.tempFile = [...formData.tempFile, files.tempFilePaths]
}

const deleteFile = (e) => {
  formData.tempFile = formData.tempFile.filter(f => f.url!== e.tempFilePath)
}

const uploadFile = async () => {
  try {
    for (let i = 0; i < formData.tempFile.length; i++) {
      for (let j = 0; j < formData.tempFile[i].length; j++) {
        const res = await http.upload('/common/upload', formData.tempFile[i][j]);
        if (formData.files === '') {
          formData.files = res.fileName;
        } else {
          formData.files = formData.files + ',' + res.fileName;
        }
        console.log(res);
      }
    }
  } catch (error) {
    console.error('文件上传过程中出现错误:', error);
    uni.showModal({
      title: '文件上传失败'+JSON.stringify(error),
      icon: 'none'
    });
  }
};

// 表单提交
const submit = async () => {
  if (formData.name === '' || formData.studentId === '' || formData.groupNum === '') {
    uni.showToast({
      title: '请填写必填项',
      icon: 'error'
    })
    return
  }
  try {
    await uploadFile()
    formData.workFile = formData.files
    const a = await http.post('/remark/project/user', formData)
    uni.$emit('refreshData', { refresh: true });
    setTimeout(() => {
      uni.navigateBack()
    }, 1000)
    uni.showToast({
      title: '提交成功',
      icon:'success'
    })
  } catch (err) {
    uni.showToast({
      title: err || '提交失败，请检查输入',
      icon: 'none'
    })
  }
}

// 初始化设置
onReady(() => {
  uni.setNavigationBarTitle({
    title: '积分申报系统'
  })
})
</script>
<style>
.container {
    height: 100vh;
    padding: 24rpx;
    background: #f8f9fa;
}

.container .submit-btn {
    margin-top: 40rpx;
    background: #409eff;
    color: white;
    border-radius: 48rpx;
}    
</style>